//
//  MovieListViewController.m
//  豆瓣终极版
//
//  Created by dllo on 15/12/18.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "MovieListViewController.h"
#import "MovieTableViewCell.h"
#import "MovieDetailViewController.h"
#import "AppTools.h"
#import "Movie.h"
#import "MJRefresh.h"
#import "MovieCollectionViewController.h"
#import "MJRefresh.h"
@interface MovieListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *movieTableView;
@property (nonatomic, retain) NSMutableArray *allArray;
@end

@implementation MovieListViewController

- (void)dealloc{
    [_movieTableView release];
    [_allArray release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.allArray = [NSMutableArray array];
    
    self.view.backgroundColor = [UIColor yellowColor];
    self.navigationItem.title = @"电影";
    // 右上角进入九宫格页面button
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_nav_collection@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnAction:)];
    
    // 创建一个电影的tableview
    self.movieTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 375, 667 - 69) style:UITableViewStylePlain];
    self.movieTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.movieTableView];
    [_movieTableView release];
    
    self.movieTableView.dataSource = self;
    self.movieTableView.delegate = self;
    
    // 注册cell
    [self.movieTableView registerClass:[MovieTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.movieTableView headerBeginRefreshing];
    // 断网缓存
    NSString *filePath = [AppTools createFilePathFromDocumentWithFolders:@[@"Movie", @"MovieList"] fileName:@"MovieList.txt"];
    NSLog(@"filePath = %@", filePath);
    
    [self.movieTableView addHeaderWithCallback:^{
        
        // 使用AFN解析电影列表数据
        [AppTools getDataWithAFNUrl:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php" block:^(id result) {
            //        NSLog(@"result = %@", result);
            NSMutableDictionary *bigDic = result;
            NSMutableArray *array = [bigDic objectForKey:@"result"];
            for (NSMutableDictionary *dic in array) {
                Movie *movie = [[Movie alloc] init];
                [movie setValuesForKeysWithDictionary:dic];
                [self.allArray addObject:movie];
                
                
            }
            // 放到主线程里
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 刷新页面
                [self.movieTableView reloadData];
            });
            
            
            NSData *data = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
            [AppTools saveDataOnLocal:data localPath:filePath];
            
            [self.movieTableView headerEndRefreshing];
        } errorBlock:^(NSError *error) {
            NSLog(@"解析失败");
            
        }];
        
        
    }];

    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [dic objectForKey:@"result"];
        for (NSMutableDictionary *dic in array) {
            Movie *movie = [[Movie alloc] init];
            [movie setValuesForKeysWithDictionary:dic];
            [self.allArray addObject:movie];
            [movie release];
        }
    }
    
    
}
// 点击切换九宫格btn事件
- (void)rightBtnAction:(UIBarButtonItem *)rightBtn{
    MovieCollectionViewController *movieCollectionVC = [[MovieCollectionViewController alloc] init];
    movieCollectionVC.array = self.allArray;
    [self.navigationController pushViewController:movieCollectionVC animated:NO];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MovieTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    // 把数据通过属性传值传给cell
    Movie *movie = [self.allArray objectAtIndex:indexPath.row];
    cell.movie = movie;
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 210;
}

// 点击cell push到详情页
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MovieDetailViewController *movieDetailVC = [[MovieDetailViewController alloc] init];
    
    // 把movieId属性传值给详情页面
    Movie *movie = [self.allArray objectAtIndex:indexPath.row];
    movieDetailVC.movieId = movie.movieId;
    // 把电影名属性传值给详情页
    movieDetailVC.movieTitle = movie.movieName;
    [self.navigationController pushViewController:movieDetailVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
